package com.plugin.storage.storage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.Instant;
import java.util.concurrent.ThreadLocalRandom;

public class StorageUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(StorageUtils.class);

    public static String getEndpoint(String urlStr) {
        try {
            URL url = new URL(urlStr);
            String protocol = url.getProtocol();
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1) {
                return String.format("%s://%s", protocol, host);
            } else {
                return String.format("%s://%s:%d", protocol, host, port);
            }
        } catch (MalformedURLException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return "";
    }

    public static String getKey(String source) {
        try {
            URI uri = new URI(source);
            return uri.getPath().replaceFirst("/", "");
        } catch (URISyntaxException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return source;
    }

    public static String removeQuery(String source) {
        try {
            URI uri = new URI(source);
            return new URI(uri.getScheme(),
                    uri.getAuthority(),
                    uri.getPath(),
                    null, // Ignore the query part of the input url
                    null).toString();
        } catch (URISyntaxException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return source;
    }

    public static String getFileName() {
        return ThreadLocalRandom.current().nextInt(100) + "" + Instant.now().getEpochSecond();
    }


    /**
     * 获取超时时间，阿里云默认1800s超时
     *
     * @return
     */
    public static long getTimestamp(int timeout) {
        long seconds = timeout - 1800;
        return Instant.now().getEpochSecond() + seconds;
    }
}
